package com.zou.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author: 邹祥发
 * @date: 2021/8/27 08:39
 */
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取路径
        String path = request.getContextPath();
        String requestURI = request.getRequestURI();
        //不过滤登录注册页面
        if (requestURI.equals(path + "/login.jsp") || requestURI.equals(path + "/register.jsp") || requestURI.equals(path + "/LoginServlet") || requestURI.equals(path + "/RegisterServlet")) {
            filterChain.doFilter(request, response);
        } else {
            //通过session获取用户信息
            HttpSession session = request.getSession();
            //session中不存在用户信息
            if (session.getAttribute("User") == null || session.getAttribute("User").equals("")) {
                session.setAttribute("msg", "请登录!");
                response.sendRedirect(path + "/login.jsp");
            } else {
                //session中存在用户信息
                filterChain.doFilter(request, response);
            }
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
